package ch.ethz.fcl.listener;

import ch.ethz.fcl.R;
import ch.ethz.fcl.googlemap.MetroBuzzGoogleMaps;
import ch.ethz.fcl.udp.UDPClient;

import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class SetButtonClickListener implements OnClickListener {
	private MapActivity ma;

	public SetButtonClickListener(MapActivity act) {
		this.ma = act;
	}

	@Override
	public void onClick(View v) {
		if (v.getTag().equals("setup")) {
			final Dialog dialog = new Dialog(ma);
			dialog.setContentView(R.layout.layout_ip);
			dialog.setTitle("IP Setting");

			Button button_ok = (Button) dialog.findViewById(R.id.button_enter);
			button_ok.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					EditText ipinput = (EditText) dialog
							.findViewById(R.id.edittext_ipaddress);
					String ip = ipinput.getText().toString();
					if (!ipValid(ip)) {
						new AlertDialog.Builder(ma)
								.setTitle("Error")
								.setMessage(
										"Invalid IP Address! Must be: [0-255].[0-255].[0-255].[0-255]")
								.setPositiveButton(
										"OK",
										new android.content.DialogInterface.OnClickListener() {
											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {
												dialog.cancel();
											}
										}).show();
					} else{
						UDPClient.ip = ip;
						dialog.dismiss();
						}
				}
			});
			dialog.show();
		} else if (v.getTag().equals("reset")){
			((MapView)ma.findViewById(R.id.mapview)).getOverlays().clear();
			((MetroBuzzGoogleMaps) ma).initOverlays();
			((MetroBuzzGoogleMaps) ma).initTimer();
			}
	}

	public boolean ipValid(String ip) {
		String[] ips = ip.split("\\.");

		for (String s : ips) {
			try {
				int num = Integer.parseInt(s);

				if (num < 0 || num > 255)
					return false;
			} catch (Exception e) {
				return false;
			}
		}

		return true;
	}

}
